const axios = require('axios')
const cheerio = require('cheerio')
const iconv = require('iconv-lite')

module.exports = async(ctx, next) => {
    var keyword = ctx.query.keyword
        // 这个网站接收的参数要经过编码
    var url = 'https://www.81book.com/search.php?keyword=' + encodeURI(keyword)
    var books = await new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: url,
            responseType: 'stream'
        }).then(res => {
            var stream = []
            res.data.on('data', st => {
                stream.push(st)
            })
            res.data.on('end', () => {
                var buffer = Buffer.concat(stream)
                let domStr = iconv.decode(buffer, 'utf8')
                var $ = cheerio.load(domStr)
                var bookArray = []
                $('.result-item').each(function() {
                    var book = {}
                    book.picUrl = $(this).find('img').attr('src')
                    book.url = $(this).find('.result-game-item-pic a').attr('href')
                    book.bookName = $(this).find('h3 span').text()
                    book.author = $(this).find('.result-game-item-info-tag').eq(0).find('span').eq(1).text().replace(/\n/gi, '').trim()
                    book.category = $(this).find('.result-game-item-info-tag').eq(1).find('span').eq(1).text()
                    book.lastChapterName = $(this).find('.result-game-item-info-tag').eq(3).find('a').text().trim()
                    bookArray.push(book)
                })
                resolve(bookArray)
            })
        })
    })
    ctx.body = books
    next()
}